package com.kbs.im.common.udp.sender;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

/**
 * udp 消息发送者业务处理类
 *
 * @author zhangzhang
 */
public class UdpSenderHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    public static Channel channel;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channel = ctx.channel();
        sendMsg();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        String response = msg.content().toString(CharsetUtil.UTF_8);
        System.out.println("收到服务器响应的消息：---->" + response);
    }

    public void sendMsg() {
        System.out.println("开始向服务器发送消息...");
        String data = "(～￣▽￣)～啦啦啦。。。。。";
        channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(data.getBytes(Charset.forName("UTF-8")))
                , new InetSocketAddress("255.255.255.255", 7777)));

    }

}